package com.wanmait.heating.webcontroller;


import com.wanmait.heating.pojo.Address;
import com.wanmait.heating.pojo.Street;
import com.wanmait.heating.pojo.Urban;
import com.wanmait.heating.pojo.Userinfo;
import com.wanmait.heating.service.AddressService;
import com.wanmait.heating.service.UrbanService;
import com.wanmait.heating.service.UserinfoService;
import com.wanmait.heating.utils.CookieUtils;
import com.wanmait.heating.utils.EncryptUtils;
import com.wanmait.heating.utils.MD5Utils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/user/usercenter")
public class UserCenterController {


    @Resource
    private AddressService addressService;
    @Resource
    private UrbanService urbanService;
    @Resource
    private UserinfoService userinfoService;

    //访问个人中心页面
    @GetMapping("index")
    public void userCenter() {
    }

    //访问个人中心菜单页面
    @GetMapping("menu")
    public void userMenu() {
    }

    //访问系统首页
    @GetMapping("system/index")
    public void systemIndex() {
    }

    //前往个人中心地址信息管理
    @GetMapping("myinfo/addressManage")
    public void addressManage() {
    }

    //访问个人资料页查询出来详细地址
    @GetMapping("myinfo/myinfo")
    public ModelAndView myinfo(HttpServletRequest request) {
        Userinfo userinfo = (Userinfo) request.getSession().getAttribute("loginUser");
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("address", addressService.selectByUserinfoId(userinfo.getId()));
        modelAndView.addObject("urbans", urbanService.findAll());
        return modelAndView;
    }


    //街道联动 根据选中的id查询所有的街道json返回
    @RequestMapping("changeUrban")
    @ResponseBody
    public List<Street> changeUrban(Integer urbanId) {
        Urban urban = urbanService.selectByUrbanId(urbanId);
        List<Street> streets = urban.getStreets();
        return streets;
    }


    //修改个人资料
    @RequestMapping("updata")
    public String updataData(HttpServletRequest request, HttpServletResponse response, MultipartFile fileToUpload, Userinfo userinfo, Address address, Integer streetId) {


        HttpSession session = request.getSession();
        Userinfo loginUser = (Userinfo) session.getAttribute("loginUser");

        //获得原始文件名
        String originalFilename = fileToUpload.getOriginalFilename();


        //查看是否更改了图片
        Userinfo userinfo1 = userinfoService.findById(loginUser.getId());
        String pic = userinfo1.getPic();
        System.out.println("图片的名称为：" + originalFilename);
        System.out.println("数据库图片为：" + pic);
        //没有更改图片
        if (originalFilename == null || originalFilename =="")
        {
            System.out.println("true");
        } else {
            System.out.println("更新图片");
            //获取文件拓展名
            String ext = FilenameUtils.getExtension(originalFilename);
            String realPath = request.getServletContext().getRealPath("/static/web/userimage");
            String fileName = UUID.randomUUID() + "." + ext;
            File file = new File(realPath, fileName);
            try {
                fileToUpload.transferTo(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
            userinfo.setPic(fileName);
            userinfo.setId(loginUser.getId());
            userinfo1.setPic(fileName);
            //更新完毕去查
            userinfoService.upDataById(userinfo);
        }
        //查看地址是否有默认地址，有的话对默认地址进行修改，没有的话对增加默认地址
        Address address1 = addressService.selectByUserinfoId(loginUser.getId());
        address.setUserinfo(loginUser);
        Street street = new Street();
        street.setId(streetId);
        address.setStreet(street);
        if (address1 == null) {
            address.setDefaultes(1);
            //增加
            addressService.insert(address);
        }
        if (address1 != null) {
            //修改默认地址
            address1.setDefaultes(0);
            addressService.update(address1);
            address.setDefaultes(1);
            addressService.insert(address);
        }

        //清空session中的数据
        session.removeAttribute("loginUser");
        //写cookie
        CookieUtils.write("name", EncryptUtils.encrypt(userinfo1.getName(), 3), "/", 60 * 60 * 24 * 30, response);
        CookieUtils.write("password", userinfo1.getPassword(), "/", 60 * 60 * 24 * 30, response);
        session.setAttribute("loginUser", userinfo1);

        return "redirect:/user/usercenter/myinfo/myinfo";
    }

    //访问密码修改页
    @GetMapping("/changePass/changePass")
    public void changePass() {

    }

    //检查密码是否正确
    @RequestMapping("/checkPass")
    @ResponseBody
    public String checkPass(String password, HttpServletRequest request) {
        HttpSession session = request.getSession();
        Userinfo loginUser = (Userinfo) session.getAttribute("loginUser");
        Userinfo userinfo = new Userinfo();
        userinfo.setName(loginUser.getName());
        userinfo.setPassword(MD5Utils.md5(password));


        Userinfo isExist = userinfoService.isExist(userinfo);
        if (isExist == null) {
            return "false";
        } else {
            return "true";
        }
    }

    //进行修改密码
    @PostMapping("/changePass/update")
    public String  updatePass(String password,HttpServletRequest request,HttpServletResponse response)
    {
       HttpSession session = request.getSession();
       Userinfo loginUser = (Userinfo)session.getAttribute("loginUser");
       loginUser.setPassword(MD5Utils.md5(password));
       userinfoService.upDataById(loginUser);
       //清空session;清空cookie
       session.removeAttribute("loginUser");
       CookieUtils.write("name", "", "/", 0, response);
       CookieUtils.write("password", "", "/", 0, response);
       return  "redirect:/user/login";

    }

//    @RequestMapping("kong")
//    public void kong()
//    {
//    }
}
